import 'package:chewie/chewie.dart';
import 'package:eyepetizer_example/widget/go_navigation.dart';
import 'package:eyepetizer_example/widget/video_controler_widget.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

class VideoPlayWidget extends StatefulWidget {

  final String playUrl;
  final bool autoPlay;
  final bool looping;
  final bool allowFullScreen;
  final bool allowPlaybackSpeedChanging;
  final double aspectRatio;

   const VideoPlayWidget({
     Key? key,
    required this.playUrl,
    this.autoPlay = true,
    this.looping = true,
    this.aspectRatio = 16/9,
    this.allowFullScreen = true,
    this.allowPlaybackSpeedChanging = true
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return VideoPlayWidgetState();
  }
}

class VideoPlayWidgetState extends State<VideoPlayWidget> {
  late VideoPlayerController _videoPlayerController;
  late ChewieController _chewieController;

  @override
  void initState() {
    super.initState();

    _videoPlayerController = VideoPlayerController.network(widget.playUrl);

    _chewieController = ChewieController(
        videoPlayerController: _videoPlayerController,
        autoPlay: widget.autoPlay,
        looping: widget.looping,
        allowFullScreen: widget.allowFullScreen,
        aspectRatio: widget.aspectRatio,
        customControls: VideoControlsWidget(
          bottomGradient: _blackLinearGradient(),
          overlayUI: _overLayUI(),
        )
    );
  }

  _overLayUI() {
    return Container(
      padding: const EdgeInsets.only(right: 8),
      decoration: BoxDecoration(gradient: _blackLinearGradient(fromTop: true)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children:   [
          BackButton(color: Colors.white,
            onPressed: (){
              GoNavigator.back(context);
            },
          ),
          const Icon(Icons.more_vert_rounded, color: Colors.white, size: 20,)
        ],
      ),
    );
  }
  /// 渐变背景色
  _blackLinearGradient({bool fromTop = false}) {
    return LinearGradient(
      begin: fromTop ? Alignment.topCenter : Alignment.bottomCenter,
      end: fromTop ? Alignment.bottomCenter : Alignment.topCenter,
      colors: const [
        Colors.black54,
        Colors.black45,
        Colors.black38,
        Colors.black26,
        Colors.black12,
        Colors.transparent
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    double height = width/widget.aspectRatio;
    return Container(
      width: width,
      height: height,
      child: Material(
          child: Chewie(controller: _chewieController,)
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _videoPlayerController.dispose();
    _chewieController.dispose();
  }

  void play(){
    _chewieController.play();
  }
  void pause(){
    _chewieController.pause();
  }

}